import { Component, OnInit, Input, SimpleChange, OnChanges, Output, EventEmitter, AfterViewInit, ɵConsole } from '@angular/core';
import { environment } from '@env/environment';
import { ArticleManegeService } from 'app/routes/main/articleManege/articleManege.service';
import { DatePipe } from '@angular/common';
import { TreeTools } from '@core/treeTools.tool';
@Component({
    selector: 'app-index-kmn-detail',
    templateUrl: './index.component.detail.html',
    styleUrls: ['./index_detail.less']
})

export class IndexKmnDetailComponent implements OnChanges, OnInit, AfterViewInit {
    selectMenuId = 0;
    showDetailPage: boolean;
    showTablePage = true;
    showMenu = true;
    private _detail = {
        detailId: 0,
        content: '',
        preTitle: '',
        preId: 0,
        nextTitle: '',
        nextId: 0,
    };

    table = {
        pageIndex: 1,
        pageSize: 10,
        total: 0,
        data: [],
    };
    /**
     * 叶子 文章类型
     */
    leafCateId: any = '';
    categoryNodes: any[] = [];
    menuNodes: any = {};

    /**
     * 传入文章ID
     */
    @Input() detailId;
    /**
     * 传入文章类型
     */
    @Input() categoryId;

    /**
     * 搜索关键词
     * 使用此属性则自动忽略其他输入属性
     */
    @Input() searchKey;

    @Output() afterInit = new EventEmitter<boolean>();
    @Output() breadChange = new EventEmitter();

    screenType = '';
    screen: any = {};
    classes: any = {};
    lastQueryParam: any = {};

    get detail() {
        return this._detail;
    }
    set detail(detail) {
        this._detail = detail;
    }

    constructor(
        private articleManegeService: ArticleManegeService,
        private datePipe: DatePipe,
        public treeTools: TreeTools,
    ) { }

    ngOnInit(): void {
        this.initScreen();
    }

    ngAfterViewInit() {
        this.afterInit.emit();
    }

    resetVar() {
        this.detail = {
            detailId: 0,
            content: '',
            preTitle: '',
            preId: 0,
            nextTitle: '',
            nextId: 0,
        };
        this.detailId = 0;
    }

    resetMenu() {
        this.menuNodes = {};
    }

    initMenu(cateId, func?) {
        if (!this.showMenu) {
            func && func();
            return;
        }
        this.getCategories(() => {
            const leafId = this.getLeafCataId(cateId);
            if (leafId) {
                this.leafCateId = leafId;
                func && func(leafId);
                const pNode = this.treeTools.getPnode({
                    id: leafId,
                    nodes: this.categoryNodes,
                    keyName: 'id',
                });
                if (pNode) {
                    this.menuNodes = pNode;
                }
                this.selectMenuId = leafId;
            }
        });
    }

    loadTableByKey(key) {
        this.showMenu = false;
        this.goTable({ title: key, pageNum: 1 });
    }

    ngOnChanges(changes: { [propKey: string]: SimpleChange }) {
        const keys = Object.keys(changes);
        let idChange;
        let id;
        let cateIdChange;
        let cateId;
        this.resetVar();
        this.resetMenu();
        if (keys.includes('searchKey')) {
            const keyChange = changes.searchKey;
            const key = keyChange.currentValue;
            if (key) {
                this.loadTableByKey(key);
                return;
            }
        }
        if (keys.includes('categoryId')) {
            cateIdChange = changes.categoryId;
            cateId = cateIdChange.currentValue;

        }
        if (keys.includes('detailId')) {
            idChange = changes.detailId;
            id = idChange.currentValue;
        }

        this.showMenu = true;
        if (id) {
            this.goDetail(id);
        } else if (cateId) {
            this.initMenu(cateId, (leafCateId) => {
                this.goTable({ category: leafCateId || this.leafCateId });
            });
        }

    }

    selectMenu(id) {
        this.categoryId = id;
        this.selectMenuId = id;
        this.goTable({ category: id });
    }

    goDetail(id) {
        this.detail.detailId = id;
        this.showDetailPage = true;
        this.showTablePage = false;
        this.getArticle(id);
    }

    goTable(param) {
        this.showDetailPage = false;
        this.showTablePage = true;
        this.getArticleList(param);
    }

    goItem(id) {
        if (!id) {
            return;
        }
        this.showMenu = true;
        this.goDetail(id);
    }

    /**
     *
     * @param param category 文章类型
     * @param param title  关键词
     * @param param article:{id:文章ID,title:文章标题}
     */
    breadChangeAfterLoad(param) {
        /**
         * type:参数类型 value?:额外需要传递的值 text:用于显示的值
         */
        const emitValues: { type: string, value?: any, text: string }[] = [];
        if (param.category) {
            const name = this.treeTools.getTreeNodeName({
                id: param.category,
                nodes: this.categoryNodes,
                keyName: 'id',
                valueName: 'text'
            });
            emitValues.push({ type: 'category', value: param.category, text: name });
        }
        if (param.title) { // 关键词
            emitValues.push({ type: 'key', text: param.title });
        }
        if (param.article) { // 根据ID查文章
            emitValues.push({ type: 'article', text: param.article.text, value: param.article.id });
        }
        this.breadChange.emit(emitValues);
    }

    getArticleList(_param) {
        const param: any = {
            size: this.table.pageSize,
            pageNum: this.table.pageIndex
        };
        Object.assign(param, _param);
        this.lastQueryParam = param;
        this.articleManegeService.queryView(param).subscribe(res => {
            for (const item of res.data) {
                if (item.summary) {
                    item.newSummary = JSON.stringify(item.summary).replace(/\&ldquo;/g, '“').replace(/\&rdquo;/g, '”').replace(/\"/g, '');
                }
            }
            this.beforeTableShow(res.data);
            this.table.data = res.data;

            this.table.total = res.totalCount;
            this.breadChangeAfterLoad(param);
        });
    }

    beforeTableShow(data) {
        data.forEach(row => {
            if (row.operTime) {
                const dateArr = this.datePipe.transform(row.operTime, 'yyyy-MM-dd').split('-');
                row._d = dateArr[2];
                row._ym = dateArr[0] + '-' + dateArr[1];
            }
        });
    }

    /**
     * 根据传入文章类型ID 返回叶子文章类型ID
     * @param articleCata 文章类型
     */
    getLeafCataId(cateId) {
        if (!cateId) {
            return;
        }
        const node = this.treeTools.getTreeNode({
            id: cateId,
            nodes: this.categoryNodes,
            keyName: 'id',
        });
        if (!node) {
            return;
        }
        const leaf = this.getFstLeaf(node);
        if (leaf) {
            return leaf.id;
        }
    }

    getFstLeaf(node) {
        if (!node.children || !node.children.length) {
            return node;
        }
        const fstChild = this.getFstChild(node);
        if (!fstChild.children || !fstChild.children.length) {
            return fstChild;
        } else {
            return this.getFstLeaf(fstChild);
        }
    }

    getFstChild(node) {
        if (node.children && node.children.length) {
            const fstChild = node.children[0];
            return fstChild;
        }
    }

    getArticle(id?) {
        this.articleManegeService.getArticleInfo(id || this.detail.detailId).subscribe(res => {
            this._detail = res;
            this.initMenu(res.category, (leafId) => {
                let breadParam = {};
                if (this.showMenu) {
                    breadParam = {
                        article: { id: res.id, text: res.title },
                        category: leafId
                    };
                } else {
                    breadParam = {
                        article: { id: res.id, text: res.title },
                        title: this.searchKey
                    };
                }
                this.breadChangeAfterLoad(breadParam);
            });
        });
    }

    pageIndexChange(v) {
        const param = { pageNum: v };
        const copy = {};
        if (this.lastQueryParam) {
            Object.assign(copy, this.lastQueryParam);
        }
        Object.assign(copy, param);
        this.getArticleList(copy);
    }
    pageSizeChange(v) {
        const param = { size: v };
        const copy = {};
        if (this.lastQueryParam) {
            Object.assign(copy, this.lastQueryParam);
        }
        Object.assign(copy, param);
        this.getArticleList(copy);
    }



    getCategories(func?) {
        if (this.categoryNodes.length) {
            func && func();
            return;
        }
        this.articleManegeService.getCategory('shouyexinwen', 1).subscribe(res => {
            this.categoryNodes = res;
            func && func();
        });
    }

    formatHref(data) {
        return environment.apiBase + '/csmis/' + data.fileUrl;
    }

    judgeScreen() {
        const screenWidth = screen.width;
        if (screenWidth <= 1280) {
            this.screenType = '3';
        } else if (screenWidth <= 1680) {
            this.screenType = '2';
        } else {
            this.screenType = '1';
        }
    }

    initScreen() {
        const spanMap = {
            '1': '4',
            '2': '2',
            '3': '1',
        };
        const siderMap = {
            '1': '13vw',
            '2': '13vw',
            '3': '15vw',
        };
        this.judgeScreen();
        this.initClasses();
        this.screen.siderWidth = siderMap[this.screenType];
        this.screen.emptyColSpan = spanMap[this.screenType];
        this.screen.mainColSpan = (24 - 2 * spanMap[this.screenType]) + '' || '16';
    }

    initClasses() {
        this.classes = {
            siderUl: `siderUl${this.screenType}`,
            tableList: `tableList${this.screenType}`,
            'menuTitleTextCn': `menu-title-text-cn${this.screenType}`,
            menus: `menus${this.screenType} menus`,
        };
    }

    getSpan(num, sum, _method) {
        const method = _method || 'floor';
        return Math[method](num / sum * this.screen.mainColSpan);
    }

}
